package com.glacier.gen.factory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.Map;

/**
 * date 2023-11-01 16:37
 *
 * @author glacier
 * @version 1.0
 */
public class TemplateEngineFactory {

    private TemplateEngineFactory() {
    }

    public static String renderString(String ftl, Map<String, ? extends Object> model) throws TemplateException, IOException {
        try (StringWriter result = new StringWriter();) {
            Template t = buildConfiguration("templates")
                    .getTemplate(ftl);
            t.process(model, result);
            return result.toString();
        }
    }

    public static Configuration buildConfiguration(String directory) throws IOException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setDirectoryForTemplateLoading(
                new File(TemplateEngineFactory.class.getClassLoader()
                        .getResource(directory)
                        .getPath()));
        return cfg;
    }

    public static void main(String[] args) {
        String directory = "templates";
        URL url = TemplateEngineFactory.class.getClassLoader()
                .getResource(directory);
        System.out.println(url);
        System.out.println(url.getPath());
    }

}
